package com.company.linkedList;

public class MergeOrderedList {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1==null) {
            return l2;
        }
        if (l2==null) {
            return l1;
        }
        return byInsert(l1,l2);
//        return byDoubleIndex(l1,l2);
    }

    private ListNode byInsert(ListNode source,ListNode insert){
        ListNode sourceIndex=source;
        ListNode insertNode=insert;

        ListNode newHead;
        if (sourceIndex.val>insertNode.val) {
            newHead = insertNode;
            insertNode = insertNode.next;
        }else {
            newHead = sourceIndex;
            sourceIndex = sourceIndex.next;
        }
        ListNode currTail=newHead;
        while (sourceIndex!=null||insertNode!=null){
            if (sourceIndex == null) {
                currTail.next = insertNode;
                insertNode = insertNode.next;
                currTail = currTail.next;
                continue;
            }

            if (insertNode == null) {
                currTail.next = sourceIndex;
                sourceIndex = sourceIndex.next;
                currTail = currTail.next;
                continue;
            }


            if (sourceIndex.val>insertNode.val) {
                  currTail.next = insertNode;
                  insertNode = insertNode.next;

            }else {
                currTail.next = sourceIndex;
                sourceIndex = sourceIndex.next;
            }
            currTail = currTail.next;
        }

        return newHead;
    }
    private ListNode byDoubleIndex(ListNode left,ListNode right){
        ListNode leftIndex = left;
        ListNode rightIndex = right;

        while (leftIndex!=null||rightIndex!=null){
            if (leftIndex.val>rightIndex.val) {

            }



        }


        return left;
    }
}
